package xin.nick.system.util;

import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import xin.nick.common.core.entity.ResultCode;

import java.util.Objects;

/**
 * @author Nick
 * @date 2022/8/10
 */
public class SecurityUtil {

    /**
     * 获取当前用户登录信息
     *
     * @return UserDetails
     */
    public static UserDetails getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (Objects.isNull(authentication)) {
            throw new InsufficientAuthenticationException(ResultCode.UNAUTHORIZED.getDescription());
        }
        return (UserDetails) authentication.getPrincipal();
    }


    /**
     * 获取当前用户登录信息,不检查登录状态
     *
     * @return UserDetails
     */
    public static UserDetails getCurrentUserNoCheck() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (Objects.isNull(authentication)) {
            return null;
        }
        return (UserDetails)authentication.getPrincipal();
    }


}
